<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告部分 -->
      <el-alert title="注意：只允许为第三级分类添加相关参数！" type="warning" show-icon :closable="false"></el-alert>
      <!-- 选择器部分 -->
      <el-row class="selectRow">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader v-model="classifyValue" :options="cateList" :props="cascaderProps" @change="cascaderChange" class="cascader"></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs栏部分 -->
      <!-- tabs 参数 
          v-model------默认展示栏
        -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <!-- many 表示动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 动态参数->按钮 -->
          <el-button type="primary" :disabled="isDisable" size="mini" @click="openManyDialog">添加参数</el-button>
          <!-- 动态参数->表格区域 -->
          <el-table :data="manyParamsList" border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(item,i) in scope.row.attr_vals" closable :disable-transitions="false" @close="manyTagClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.tabInputVisible" v-model="scope.row.inputVals" ref="tagInput" size="small" @keyup.enter.native="tabInputConfirm(scope.row)" @blur="tabInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- only 表示静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 静态属性->按钮 -->
          <el-button type="primary" :disabled="isDisable" size="mini" @click="openOnlyDialog">添加属性</el-button>
          <!-- 静态属性->表格区域 -->
          <el-table :data="onlyParamsList" border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(item,i) in scope.row.attr_vals" closable :disable-transitions="false" @close="manyTagClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.tabInputVisible" v-model="scope.row.inputVals" ref="tagInput" size="small" @keyup.enter.native="tabInputConfirm(scope.row)" @blur="tabInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加弹出框区域 -->
    <el-dialog :title="'添加'+dialogName" :visible.sync="addDialogVisible" width="50%" @close="closeAddDialogClose">
      <el-form ref="addForm" :model="addFormData" label-width="80px" :rules="addFormRules">
        <el-form-item :label="dialogName" prop="attr_name">
          <el-input v-model="addFormData.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendaddRequest">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑弹出框区域 -->
    <el-dialog :title="'编辑'+dialogName" :visible.sync="EditDialogVisible" width="50%" @close="closeEditDialogClose">
      <el-form ref="editForm" :model="editFormData" label-width="80px" :rules="addFormRules">
        <el-form-item :label="dialogName" prop="attr_name">
          <el-input v-model="editFormData.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
import $http from '@/utils/resquest.js'
export default {
  data() {
    return {
      // 商品分类选择器数组
      classifyValue: [],
      // 商品分类数据
      cateList: [],
      // 选择器的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },

      // tabs默认展示栏
      activeName: 'many',
      // 动态参数数据
      manyParamsList: [],
      // 静态属性数据
      onlyParamsList: [],
      // 控制添加对话框开关
      addDialogVisible: false,
      // 添加数据表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      // 表单数据
      addFormData: {
        attr_name: ''
      },

      // 控制编辑对话框开关
      EditDialogVisible: false,
      // 添加数据表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      // 表单数据
      editFormData: {
        attr_name: ''
      },
      attrId: '',

      // 控制标签内容
      attrVals: ''
    }
  },
  methods: {
    // 动态参数标签关闭
    manyTagClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.sendTabRequset(row)
    },
    async sendTabRequset(row) {
      const { data: res } = await $http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_sel: this.activeName,
        attr_name: row.attr_name,
        attr_vals: row.attr_vals.toString()
      })
      if (res.meta.status !== 200) {
        return this.$message.error('操作失败')
      }
      console.log(res.data)
      this.$message.success('操作成功')
    },
    // 标签文本框失去焦点
    tabInputConfirm(row) {
      // 如果输入空字符
      if (row.inputVals.trim().length == 0) {
        row.inputVals = ''
        row.tabInputVisible = false
        return
      }
      row.attr_vals = [...row.attr_vals, row.inputVals]
      // console.log(row.attr_vals);
      this.sendTabRequset(row)
      row.inputVals = ''
      console.log('标签文本框失去焦点' + row.inputVals)
      row.tabInputVisible = false
    },
    // 显示输入框
    showInput(row) {
      row.tabInputVisible = true
      this.$nextTick(() => {
        this.$refs.tagInput.$refs.input.focus()
      })
    },

    // 删除
    async deleteParams(row) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await $http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除失败！')
      this.$message.success('删除成功！')
      this.getParamsList()
    },

    // 编辑
    editParams() {
      this.$refs.editForm.validate(async v => {
        if (!v) return this.$message.warning('请填写数据')
        const { data: res } = await $http.put(`categories/${this.cateId}/attributes/${this.attrId}`, {
          attr_sel: this.activeName,
          attr_name: this.editFormData.attr_name
        })
        if (res.meta.status !== 200) {
          this.EditDialogVisible = false
          return this.$message.error('数据获取失败')
        }
        this.$message.success('编辑成功')
        this.getParamsList()
      })
      this.EditDialogVisible = false
    },
    // 打开编辑对话框
    openEditDialog(row) {
      this.EditDialogVisible = true
      this.editFormData.attr_name = row.attr_name
      this.attrId = row.attr_id
    },
    // 编辑对话框关闭
    closeEditDialogClose() {
      // 重置数据
      this.$refs.editForm.resetFields()
    },

    // 添加/添加属性
    async sendaddRequest() {
      this.$refs.addForm.validate(async v => {
        if (!v) return this.$message.warning('请填写数据')
        const { data: res } = await $http.post(`categories/${this.cateId}/attributes`, {
          attr_sel: this.activeName,
          attr_name: this.addFormData.attr_name
        })
        if (res.meta.status !== 201) {
          this.addDialogVisible = false
          return this.$message.error('数据获取失败')
        }
        this.$message.success('添加成功')
        this.getParamsList()
      })
      this.addDialogVisible = false
    },
    // 打开参数对话框
    openManyDialog() {
      // 添加数据
      this.addDialogVisible = true
    },
    // 打开属性对话框
    openOnlyDialog() {
      this.addDialogVisible = true
    },
    // 对话框添加关闭
    closeAddDialogClose() {
      // 重置数据
      this.$refs.addForm.resetFields()
    },

    // tabs的点击事件
    handleTabsClick() {
      this.cascaderChange()
    },
    // 选择器发生变化时
    cascaderChange() {
      // 判断选择的是否是三级分类
      if (this.classifyValue.length !== 3) {
        this.classifyValue = []
        this.manyParamsList = []
        this.onlyParamsList = []
        return
      }
      this.getParamsList()
    },
    // 获取分类参数数据
    async getParamsList() {
      const { data: res } = await $http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('数据获取失败')
      // 把数据做一下修改:把字符串转换为数组
      res.data.forEach(item => {
        // 判断attr_vals是否为空
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 添加用于控制文本框的显示与隐藏
        item.tabInputVisible = false
        // 初始值
        item.inputVals = ''
      })
      console.log(res.data)
      if (this.activeName == 'many') {
        this.manyParamsList = res.data
      } else {
        this.onlyParamsList = res.data
      }
    },
    // 为选择器获取数据，商品分类数据
    async getCateList() {
      const { data: res } = await $http.get('categories')
      // console.log(res.data)
      if (res.meta.status !== 200) return this.$message.error('数据获取失败')
      this.cateList = res.data
    }
  },
  created() {
    this.getCateList()
  },
  // 计算属性
  computed: {
    // 控制按钮是否可用
    isDisable() {
      // 不等于3，返回true（禁用），否则返回false（可用）
      return this.classifyValue.length !== 3
    },
    // 计算选择器发生变化时，对应分类的id
    cateId() {
      if (this.classifyValue.length !== 3) return null
      return this.classifyValue[this.classifyValue.length - 1]
    },
    // 控制 对话框名称
    dialogName() {
      return this.activeName == 'many' ? '动态参数' : '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.selectRow {
  margin: 15px 0;
}
.cascader {
  width: 300px;
}
.el-tag + .el-tag {
  margin: 6px;
}
.input-new-tag {
  width: 120px;
}
</style>
